<?php
session_start();

if (!isset($_SESSION['uid']))
{
	header('Location:index.php?redirection=' . urlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_StrING']));
	exit;
}
include('config.php');
('udf_functions.php');
if(!isset($_POST['submit']))
{
        if (!isset($_REQUEST['last_message']))
        {
                $_REQUEST['last_message']='';
        }
	draw_header('Add New File');
	draw_menu($_SESSION['uid']);
	draw_status_bar('Add new document', $_REQUEST['last_message']);
	echo '<body';
	echo '<center>'."\n".'<table border="0" cellspacing="5" cellpadding="5">'."\n";
	
	//////////////////////////Get Current User's department id///////////////////
	$query ="SELECT department FROM {$GLOBALS['CONFIG']['db_prefix']}user where id='$_SESSION[uid]'";
	$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
	if(mysql_num_rows($result) != 1) 
	{
		header('Location:error.php?ec=14');
		exit; 
	}
	list($current_user_dept) = mysql_fetch_row($result);

	$query = "SELECT name, id FROM {$GLOBALS['CONFIG']['db_prefix']}department ORDER by name";
	$result = mysql_query ($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
	$dept_data = $result;
	$index = 0;

	?>
	<script type="text/javascript">
	

	function Department(name, id, rights)
    		{
       			this.name = name;
        		this.id = id;
        		this.rights = rights;
        		this.isset_flag = false;
        		if (typeof(_department_prototype_called) == "undefined")
        		{
             			_department_prototype_called = true;
            		 	Department.prototype.getName = getName;
            			Department.prototype.getId = getId;
            			Department.prototype.getrights = getrights;
             			Department.prototype.setName = setName;
            	 		Department.prototype.setId = setId;
             			Department.prototype.setrights = setrights;
             			Department.prototype.issetFlag = issetFlag;
             			Department.prototype.setFlag = setFlag;

        		}
	    		function setFlag(set_boolean)
	    		{	this.isset_flag = set_boolean;	}

       			function getName()
        		{       return this.name;		}

       			function getId()
        		{       return this.id;	                }
			
				function getrights()
				{	return parseInt(this.rights);		}

				function setrights(rights)
        		{       this.rights = parseInt(rights); }

       	 		function setName(name)
        		{       this.name = name;               }

				function setId(id)
            	{       this.id = id;         }

				function issetFlag()
            	{       return this.isset_flag;         }
    		}
	
	
	var default_Setting_pos = 0;
	var all_Setting_pos = 1;
	var departments = new Array();
	var default_Setting = new Department("Default Setting for Unset Department", "0", "0");
	var all_Setting = new Department("All", "0", "0");
	departments[all_Setting_pos] = all_Setting; 
	departments[default_Setting_pos] = default_Setting;
	
	/////////////////////////Populate Department obj////////////////////////////////
<?php
	while( list($dept_name, $dept_id) = mysql_fetch_row($result) ) {
		if($dept_id == $current_user_dept) {         
			echo 'departments[' . ($index+2) . '] = new Department("' . $dept_name . '", "' . $dept_id . '", "1")' . "\n";
		}
		else {
            echo 'departments[' . ($index+2) . '] = new Department("' . $dept_name . '", "' . $dept_id . '", "0")' . "\n";
        }
		$index++;
	}
?>
	</script>
	<script type="text/javascript"src="functions.js"></script>

	<form name="main" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
	<input type="hidden" name="MAX_FILE_SIZE" value="50000000">
		<tr>
			<td>
				File Location
			</td>
			<td colspan=3><input tabindex="0" name="file" type="file">
			</td>
		</tr>
		<tr>
			<td>
				Category
			</td>
			<td colspan=3><select tabindex="1" tabindex=2 name="category" >
		<?php
			/////////////// Populate category drop down list//////////////
			$query = "SELECT id, name FROM {$GLOBALS['CONFIG']['db_prefix']}category ORDER BY name";
			$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
			while(list($id, $name) = mysql_fetch_row($result)) { 
				echo '<option value="' . $id . '">' . $name . '</option>'; 
			}
			mysql_free_result ($result);
		?>
			</select>
			</td>
		</tr>
<?php
	udf_add_file_form();
?>
	<!-- Set Department rights on the file -->
        <tr>
	<td>
		Department
	</td>
     		<td COLSPAN=3><SELECT tabindex=3 NAME="dept_drop_box" onChange ="loadDeptdata(this.selectedIndex)">
				<option value=0> Select a Department</option>
				<option value=1> Default Setting for Unset Department</option>
				<option value=2> All Departments</option>
<?php
	//////Populate department drop down list/////////////////
   	$query = "SELECT id, name FROM {$GLOBALS['CONFIG']['db_prefix']}department ORDER BY name";
   	$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());

  	while(list($id, $name) = mysql_fetch_row($result))
    {
    	$id+=2;

		echo '	<option value ="' . $id . '" name="' . $name . '">'. $name . '</option>' . "\n";  
    }
	mysql_free_result ($result);
?>
    </SELECT>
	</td>
    </tr>
    <tr>
		<td>
			Authority
		<td/>

	<td>
<?php
      	$query = "SELECT RightId, Description FROM {$GLOBALS['CONFIG']['db_prefix']}rights order by RightId";
      	$result = mysql_query($query, $GLOBALS['connection']) or die("Error in querry: $query. " . mysql_error());
      	while(list($RightId, $Description) = mysql_fetch_row($result))
      	{	
      		echo $Description.'<input type ="radio" name ="'.$Description.'" value="' . $RightId . '" onClick="setdata(this.name)"> |'."\n";
		}     
?>
	</td>
	</tr>
	<tr>
	<td>
        Description
        </td>
	<td colspan="3"><input tabindex="5" type="Text" name="description" size="50"></td>
	</tr>
	
	<tr>
	<td>
        Comment
    </td>
	<td colspan="3"><textarea tabindex="6" name="comment" rows="4" onchange="this.value=enforceLength(this.value, 255);"></textarea></td>
	</tr>

	<TABLE border="0" cellspacing="0" cellpadding="3" NOWRAP>
	<tr nowrap>
	  <td colspan="2" NOWRAP><b>Specific Permissions Settings</b></td>
	</tr>
	<tr>
	<td valign="top" align="center">Forbidden</td>
	<td valign="top" align="center">View</td>
	<td valign="top" align="center">Read</td>
	<td valign="top" align="center"><Modify</td>
	<td valign="top" align="center">Admin</td>
	</tr>
	<tr>
	<td><select tabindex="8" name="forbidden[]" multiple size="10" onchange="changeForbiddenList(this, this.form);">
<?php
	
		$query = "SELECT id, last_name, first_name FROM {$GLOBALS['CONFIG']['db_prefix']}user ORDER BY last_name";
		$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
		//////////////////Forbidden////////////////////
		while(list($id, $last_name, $first_name) = mysql_fetch_row($result))
		{
			$str = '<option value="' . $id . '"';
			$str .= '>'.$last_name.', '.$first_name.'</option>';
			echo $str;
		}
		mysql_free_result ($result);
?>
	</select></td>
	<td><select tabindex="9" name="view[]" multiple size="10" onchange="changeList(this, this.form);">
<?php 
		////////////////////View//////////////////////////
		$query = "SELECT id, last_name, first_name FROM {$GLOBALS['CONFIG']['db_prefix']}user ORDER BY last_name";
		$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
		//////////////////Forbidden////////////////////
		while(list($id, $last_name, $first_name) = mysql_fetch_row($result))
		{
			$str = '<option value="' . $id . '"';
			if($id == $_SESSION['uid']) {$str .= ' selected';}
			$str .= '>'.$last_name.', '.$first_name.'</option>';
			echo $str;
		}
		mysql_free_result ($result);
?>
	</SELECT></td>
	<td><select tabindex="10"  name="read[]" multiple size="10"onchange="changeList(this, this.form);">
<?php
	////////////////////Read//////////////////////////
	$query = "SELECT id, last_name, first_name FROM {$GLOBALS['CONFIG']['db_prefix']}user ORDER BY last_name";
		$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
		//////////////////Forbidden////////////////////
		while(list($id, $last_name, $first_name) = mysql_fetch_row($result))
		{
			$str = '<option value="' . $id . '"';
			
			if($id == $_SESSION['uid']) {$str .= ' selected';}
			$str .= '>'.$last_name.', '.$first_name.'</option>';
			echo $str;
		}
		mysql_free_result ($result);
?>
	</SELECT></td>
	<td><select tabindex="11" name="modify[]" multiple size="10"onchange="changeList(this, this.form);">
<?php
	////////////////////Read//////////////////////////
		$query = "SELECT id, last_name, first_name FROM {$GLOBALS['CONFIG']['db_prefix']}user ORDER BY last_name";
		$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
		//////////////////Forbidden////////////////////
		while(list($id, $last_name, $first_name) = mysql_fetch_row($result))
		{
			$str = '<option value="' . $id . '"';
			if($id == $_SESSION['uid']) {$str .= ' selected';}
			$str .= '>'.$last_name.', '.$first_name.'</option>';
			echo $str;
		}
		mysql_free_result ($result);
?>
	</SELECT></td>
	<td><select tabindex="12" name="admin[]" multiple size="10" onchange="changeList(this, this.form);">
<?php
	////////////////////Read//////////////////////////
		$query = "SELECT id, last_name, first_name FROM {$GLOBALS['CONFIG']['db_prefix']}user ORDER BY last_name";
		$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
		//////////////////Forbidden////////////////////
		while(list($id, $last_name, $first_name) = mysql_fetch_row($result))
		{
			$str = '<option value="' . $id . '"';
			if($id == $_SESSION['uid']) {$str .= ' selected';}
			$str .= '>'.$last_name.', '.$first_name.'</option>';
			echo $str;
		}
		mysql_free_result ($result);
?>	</SELECT></td>
	
	</tr>
	</TABLE>
	<tr>
	<td colspan="4" align="center"><input tabindex=7 type="Submit" name="submit" value="Add Document"></td>
	</tr>
<?php	
		$query = "SELECT name, id FROM {$GLOBALS['CONFIG']['db_prefix']}department ORDER BY name";
		$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
		while( list($dept_name, $dept_id) = mysql_fetch_row($result) )
		{		
			if($dept_id == $current_user_dept)
				echo "\n\t".'<input type="hidden" name="'. space_to_underscore($dept_name).'" value="1"> '."\n";
			else
				echo "\n\t".'<input type="hidden" name="'.space_to_underscore($dept_name).'" value="0"> '."\n";
		}
		echo "\n\t".'<input type="hidden" name="default_Setting" value="0"> '."\n";
		mysql_free_result ($result);
?>
	</form>
	</table>
	</center>
<?php
draw_footer();
}
else 
{
	for($khoa = 0; $khoa<1; $khoa++)
	{
		if ($GLOBALS['CONFIG']['authorization'] == 'On')
			$lpublishable = '0';
		else
			$lpublishable= '1';
	$result_array = array();

	$query ="SELECT department FROM {$GLOBALS['CONFIG']['db_prefix']}user where id=$_SESSION[uid]";
	$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
	if(mysql_num_rows($result) != 1)
	{
		header('Location:error.php?ec=14');
		exit; 
	}
	list($current_user_dept) = mysql_fetch_row($result);

	if ($_FILES['file']['size'] <= 0 )
	{ 
		header('Location:error.php?ec=11'); 
		exit; 
	}

    if($_FILES['file']['size'] >  $GLOBALS['CONFIG']['max_filesize'] ) 
    {
		header('Location:error.php?ec=25'); 
		exit; 
	}
        
	$allowedFile = 0;
	foreach($allowedFileTypes as $thistype)
	{
        if ($_FILES['file']['type'] == $thistype) 
        { 
            $allowedFile = 1;
            break; 
        } 
    }	

	if (!isset($allowedFile)) 
	{ 
		header('Location:error.php?ec=13&last_message=MIMETYPE+failed+' . $_FILES['file']['type']); 
		exit; 
	}

        if (!is_dir($GLOBALS['CONFIG']['dataDir']))
        {
                $last_message=$GLOBALS['CONFIG']['dataDir'] . ' missing!';
                header('Location:error.php?ec=23&last_message=' .$last_message);
                exit;
        }
        else
        {
                if (!is_writeable($GLOBALS['CONFIG']['dataDir']))
                {
                        $last_message='Folder Permissions Error: ' . $GLOBALS['CONFIG']['dataDir'] . ' not writeable!';
                        header('Location:error.php?ec=23&last_message=' .$last_message);
                        exit;
                }
        }
	$query = "INSERT INTO {$GLOBALS['CONFIG']['db_prefix']}data (status, category, owner, realname, created, description, department, comment, default_rights, publishable) VALUES(0, '" . addslashes($_REQUEST['category']) . "', '" . addslashes($_SESSION['uid']) . "', '" . addslashes($_FILES['file']['name']) . "', NOW(), '" . addslashes($_REQUEST['description']) . "','" . addslashes($current_user_dept) . "', '" . addslashes($_REQUEST['comment']) . "','" . addslashes($_REQUEST['default_Setting']) . "', $lpublishable )";
	$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
	
	$fileId = mysql_insert_id($GLOBALS['connection']);

	udf_add_file_insert($fileId);
	
	$query = "SELECT username FROM {$GLOBALS['CONFIG']['db_prefix']}user where id='$_SESSION[uid]'";
	$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
	list($username) = mysql_fetch_row($result);
	
	$query = "INSERT INTO {$GLOBALS['CONFIG']['db_prefix']}log (id,modified_on, modified_by, note, revision) VALUES ( '$fileId', NOW(), '" . addslashes($username) . "', 'Initial import', 'current')";
	$result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
	

	$query = "SELECT name, id FROM {$GLOBALS['CONFIG']['db_prefix']}department ORDER BY name";
	$result = mysql_query($query, $GLOBALS['connection']) or die("Error in query: $query. " . mysql_error() );
	while( list($dept_name, $id) = mysql_fetch_row($result) )
	{
		$query = "INSERT INTO {$GLOBALS['CONFIG']['db_prefix']}dept_perms (fid, rights, dept_id) VALUES('$fileId', '" . addslashes($_REQUEST[space_to_underscore($dept_name)]) . "', '$id')";
		$result2 = mysql_query($query, $GLOBALS['connection']) or die("Error in query: $query. " . mysql_error() );
	}
	$filedata = new FileData($fileId, $GLOBALS['connection'], $GLOBALS['database']);	

        if  (isset ($_REQUEST['admin']))
        {
	        $result_array = advanceCombineArrays($_REQUEST['admin'], $filedata->ADMIN_RIGHT, $_REQUEST['modify'], $filedata->WRITE_RIGHT);
        }

        if (isset ($_REQUEST['read']))
        {
	        $result_array = advanceCombineArrays($result_array, 'NULL', $_REQUEST['read'], $filedata->READ_RIGHT);
        }

        if (isset ($_REQUEST['view']))
        {
	        $result_array = advanceCombineArrays($result_array, 'NULL', $_REQUEST['view'], $filedata->VIEW_RIGHT);
        }

        if (isset ($_REQUEST['forbidden']))
        {
        	$result_array = advanceCombineArrays($result_array, 'NULL', $_REQUEST['forbidden'], $filedata->FORBIDDEN_RIGHT);
        }
        for($i = 0; $i<sizeof($result_array); $i++)
	{
		$query = "INSERT INTO {$GLOBALS['CONFIG']['db_prefix']}user_perms (fid, uid, rights) VALUES('$fileId', '".$result_array[$i][0]."','". $result_array[$i][1]."')";
		$result = mysql_query($query, $GLOBALS['connection']) or die("Error in query: $query" .mysql_error());;
	}

	$newFileName = $fileId . '.dat';
	
	if($khoa==0)
	{
		if (!is_uploaded_file ($_FILES['file']['tmp_name']))
		{
			header('Location: error.php?ec=18');
			exit;
		}
		move_uploaded_file($_FILES['file']['tmp_name'], $GLOBALS['CONFIG']['dataDir'] . '/' . $newFileName);
	}
	else
		copy($GLOBALS['CONFIG']['dataDir'] . '/' . ($fileId-1) . '.dat', $GLOBALS['CONFIG']['dataDir'] . '/' . $newFileName);
	$message = urlencode('Document successfully added');
	header('Location: out.php?last_message=' . $message);
	}
}
?>
<script type="text/javascript">

    var index = 0;
    var index2 = 0;
    var begin_Authority;
    var end_Authority;
    var frm_main = document.main;
    var dept_drop_box = frm_main.dept_drop_box;
    while(frm_main.elements[index].name != "forbidden")
    {       index++;        }
	index2 = index;         
    while(frm_main.elements[index2].name != "admin")
    {       index2++;       }
    
    begin_Authority = index;
    end_Authority = index2;
/////////////////////////////Defining event-handling functions///////////////////////////////////////////////////////
    var num_of_authorities = 4;
    function showData()
	{
		alert(frm_main.elements["Information_Systems"].value);
		alert(frm_main.elements["Test"].value);
		alert(frm_main.elements["Toxicology"].value);
	}
	function test()
	{
		alert(frm_main.elements["default_Setting"].value);
	}
	
	
	function loadDeptdata(_selectedIndex)
    {
        if(_selectedIndex > 0)  
        {
	        switch(departments[(_selectedIndex-1)].getrights())
	        {
	        	case -1: 
		        	frm_main.forbidden.checked = true;
					deselectOthers("forbidden");
					break;
				case 0:
		            frm_main.none.checked = true;
					deselectOthers("none");
					break;
				case 1:
		            frm_main.view.checked = true;
					deselectOthers("view");
		            break;
		        case 2:
					frm_main.read.checked = true;
					deselectOthers("read");
		        	break;
		        case 3:
					frm_main.write.checked = true;
		            deselectOthers("write");
		            break;
		        case 4:
					frm_main.admin.checked = true;
					deselectOthers("admin");
		           	break;				
				default: break;
			}
	    }
	    else
	    {
			index = begin_Authority;
	        while(index <= end_Authority)
	        {
				frm_main.elements[index++].checked = false;
	        }
	   	}
    }
	
	
	function deselectOthers(selected_rb_name)
    {
		var index = begin_Authority;
        while(index <= end_Authority)
        {
			if(frm_main.elements[index].name != selected_rb_name)
           	{
            	frm_main.elements[index].checked = false;
           	}
			index++;
        }
    }
	
	function spTo_(string)
	{
		var pattern = / /g;
		return string.replace(pattern, "_");
	}
	
	function setdata(selected_rb_name)
    {
		var index = 0;
		var current_selected_dept =  dept_drop_box.selectedIndex - 1;
		var current_dept = departments[current_selected_dept];
		deselectOthers(selected_rb_name);
		departments[current_selected_dept].setrights(frm_main.elements[selected_rb_name].value); 
		if(current_selected_dept-2 >= 0) 
		{
			
			frm_main.elements[spTo_( current_dept.getName() )].value = current_dept.getrights();		
		}
		departments[current_selected_dept].setFlag("true");
		if(  current_selected_dept == default_Setting_pos )  //for default user option
        {
        	frm_main.elements['default_Setting'].value = frm_main.elements[selected_rb_name].value
        	while (index< dept_drop_box.length)
            {
				if(departments[index].issetFlag() == false && index != all_Setting_pos && index != default_Setting_pos)
                {
					departments[index].setrights(frm_main.elements[selected_rb_name].value); 

					frm_main.elements[spTo_(departments[index].getName())].value = frm_main.elements[selected_rb_name].value;
				}
                index++;
            }
			index = 0;
        }
		if( current_selected_dept == all_Setting_pos) 
		{
			index = 0;
			while(index < dept_drop_box.length)
			{
				if(index != default_Setting_pos && index != all_Setting_pos) 
				{
					departments[index].setFlag(true);

					departments[index].setrights(frm_main.elements[selected_rb_name].value );

					frm_main.elements[spTo_(departments[index].getName())].value = frm_main.elements[selected_rb_name].value;
				}
				index++;
			}
		} 
	}
	function changeList(select_list, current_form)
	{
		var select_list_array = new Array();
		select_list_array[0] = current_form['view[]']; 
		select_list_array[1] = current_form['read[]']; 
		select_list_array[2] = current_form['modify[]'];
		select_list_array[3] = current_form['admin[]'];
		for( var i=0; i < select_list_array.length; i++)
		{
			if(select_list_array[i] == select_list)
			{
				for(var j=0; j< select_list.options.length; j++)
				{
					if(select_list.options[j].selected)
					{
						for(var k=0; k < i; k++)
						{
							select_list_array[k].options[j].selected=true;	
						}
						current_form['forbidden[]'].options[j].selected=false;
					}
					else
					{
						for(var k=i+1; k < select_list_array.length; k++)
						{
							select_list_array[k].options[j].selected=false;
						}
					}
				}
			}
		}
	}
	function changeForbiddenList(select_list, current_form)
	{
		var select_list_array = new Array();
		select_list_array[0] = current_form['view[]']; 
		select_list_array[1] = current_form['read[]']; 
		select_list_array[2] = current_form['modify[]'];
		select_list_array[3] = current_form['admin[]'];
		for(var i=0; i < select_list.options.length; i++)
		{
			if(select_list.options[i].selected==true)
			{
				for( var j=0; j < select_list_array.length; j++)
				{
					select_list_array[j].options[i].selected=false;	
				}
			}
		} 
	}

</script>

